package com.thread.async;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author wangyingjie
 * @date
 * @remark 读读并行，写写互斥
 */
public class ReadWriteLockDemo {

//    private static ReentrantLock lock = new ReentrantLock();

    /**
     * 读写锁
     */
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 读锁：读读并行，读写堵塞
     */
    private static Lock readLock = readWriteLock.readLock();

    /**
     * 写锁：读写堵塞，写写堵塞
     */
    private static Lock writeLock = readWriteLock.writeLock();


    private int value;

    /**
     * 读操作
     * @param lock
     */
    public int read(Lock lock){
        lock.lock();
        System.out.println("开始读。。。");
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return value;
    }

    /**
     * 写操作
     * @param lock
     */
    public int write(Lock lock,int value){
        lock.lock();
        System.out.println("开始写。。。");
        try {
            Thread.sleep(1000);
            this.value= value;

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return value;
    }


    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            Thread readThread = new Thread() {
                @Override
                public void run() {
//                    demo.read(lock);
                //用读锁的时候是并行的
//                demo.read(readLock);
//                demo.write(lock, index);
                //用写锁是堵塞的串行
                demo.write(writeLock,index);
                }
            };
            readThread.start();
        }


    }
}
